package com.gitee.yusugar.core.annotation;

import cn.hutool.core.util.StrUtil;
import com.gitee.yusugar.core.util.FileUtil;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;

public class InitFileUtilByImportSelector implements ImportBeanDefinitionRegistrar, EnvironmentAware {

    private Environment environment;

    @Override
    public void registerBeanDefinitions( AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry ) {
        AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap( annotationMetadata.getAnnotationAttributes( EnableFileUpload.class.getName() ) );

        if ( annotationAttributes != null ) {
            // 获取 配置文件 里的值，与注解里的值（优先使用配置文件里的值）
            String propPath = environment.getProperty( "file.upload.path" );
            FileUtil.path = StrUtil.isBlank( propPath ) ? annotationAttributes.getString( "path" ) : propPath;

            String propCutPath = environment.getProperty( "file.upload.cut-path" );
            FileUtil.cutPath = StrUtil.isBlank( propCutPath ) ? annotationAttributes.getString( "cutPath" ) : propCutPath;

            String propAccessAddr = environment.getProperty( "file.upload.access-addr" );
            FileUtil.accessAddr = StrUtil.isBlank( propAccessAddr ) ? annotationAttributes.getString( "accessAddr" ) : propAccessAddr;
        }
    }

    @Override
    public void setEnvironment( Environment environment ) {
        this.environment = environment;
    }
}
